package com.dominator.utils.ocr;


import com.dominator.enums.ReqEnums;
import com.dominator.utils.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Slf4j
public class BaiduOcrUtils {


    public static void main(String[] args) throws IOException {
        String filePath = "D:/1.jpg";
        byte[] imgData = FileUtil.readFileByBytes(filePath);
        log.info(getOcrResult(imgData));
    }


    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String access_token ="";
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                log.info((key + "--->" + map.get(key)));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            log.info("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            access_token = jsonObject.getString("access_token");
        } catch (Exception e) {
            log.error("获取token失败!");
            throw new ApiException(ReqEnums.OCR_ERROR);

        }
        return access_token;
    }


//    本地图片路径
//    String filePath = "D:/10221433.png";
//    byte[] imgData = FileUtil.readFileByBytes(filePath);



    /**
     * 获取ocr结果
     * @param imgData
     * @return
     */
    public static String getOcrResult(byte[] imgData){
        String otherHost = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";
        String result ="";
        try {
            String imgStr = Base64Util.encode(imgData);
            String params = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(imgStr, "UTF-8");
            String accessToken = getAuth("SmqEA5ZzWuFlqgVIDqVm6d8q", "6gYXi0fkSA424CwXhjcfYUYxRMpK4BUu ");
            result = HttpUtil.post(otherHost, accessToken, params);
            log.info("result="+result);
        } catch (Exception e) {
            throw new ApiException(ReqEnums.OCR_ERROR);
        }

        return  result;
    }

    /**
     * 获取ocr结果
     * @param base64Str
     * @return
     */
    public static String getOcrResult(String base64Str){
        String otherHost = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";
        String result ="";
        try {
            if (base64Str.contains(",")){
                base64Str=base64Str.split(",")[1];
            }
            log.info("base64Str="+base64Str);
            String params = URLEncoder.encode("image", "UTF-8") + "=" +URLEncoder.encode(base64Str,"UTF-8");
            String accessToken = getAuth("SmqEA5ZzWuFlqgVIDqVm6d8q", "6gYXi0fkSA424CwXhjcfYUYxRMpK4BUu ");
            result = HttpUtil.post(otherHost, accessToken, params);
            log.info("result="+result);
        } catch (Exception e) {
            throw new ApiException(ReqEnums.OCR_ERROR);
        }
        return  result;
    }

}







